package com.petrooil.web.validator;

import com.petrooil.core.model.controller.ModelUser;
import com.petrooil.core.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

@Repository
public class UserValidator implements Validator {

    @Autowired
    private IUserService userService;

    @Override
    public boolean supports(Class<?> aClass) {
        return ModelUser.class.isAssignableFrom(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password",
                "required.password", "Pole 'Hasło' jest wymagane.");

//        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "rePassword",
//                "required.re-password", "Field name is required.");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login",
                "required.login", "Pole 'Login' jest wymagane.");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "roles",
                "required.roles", "Pole 'Role' jest wymagane.");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "departments",
                "required.departments", "Pole 'Dział' jest wymagane.");

        ModelUser modelUser = (ModelUser) o;

        if(!(modelUser.getPassword().equals(modelUser.getRePassword()))){
            errors.rejectValue("password", "notmatch.password");
        }

        if (modelUser.getLogin() != null && userService.get(modelUser.getLogin()) != null) {
            errors.rejectValue("login", "user.exist");
        }

    }
}
